#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;
#include "UdpServer.hpp"
#include "Log.hpp"
#include <cstdio>

void Usage(char *head)
{
    cout << "Use Err" << endl;
    cout << head << "port" << endl;
}

vector<string> DangerCommand()
{
    vector<string> ret{
        "rm",
        "unlink",
        "cp",
        "mv",
        "chmod",
        "exit",
        "reboot",
        "halt",
        "shutdown",
        "top",
        "kill",
        "dd",
        "vim",
        "vi",
        "nano",
        "man"};
    return ret;
}

bool Check(const string &mes)
{
    vector<string> danger = DangerCommand();
    for (auto &e : danger)
    {
        if (mes.find(e) != string::npos)
            return false;
    }

    return true;
}

string RunResult(string mes)
{
    if (!Check(mes))
        return "bad man~~~!!!";

    cout << "get a message: " << mes << endl;
    ;
    FILE *file = popen(mes.c_str(), "r");
    string ret;
    char buffer[1024];
    while (true)
    {
        char *a = fgets(buffer, sizeof(buffer), file);
        if (a == nullptr)
            break;
        else
            ret += buffer;
    }
    pclose(file);
    return ret.empty()? "get some success": ret;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
    }

    // string ip = argv[1];
    uint16_t port = stoi(argv[1]);

    std::unique_ptr<UdpServer> usvr(new UdpServer(RunResult, port));

    usvr->Init();
    usvr->Start();

    return 0;
}